package com.demo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller    // 表示这是一个Controller
@RequestMapping(path="/spring") // 访问url从Application/spring/开始
public class MainController {
	
    @Autowired//自动从spring容器中加载userRepository
    private UserRepository userRepository;

    @GetMapping(path="/add") // “/add”路径映射到addNewUser方法上
    public @ResponseBody String addNewUser (@RequestParam String name
            , @RequestParam String email) {
        // @ResponseBody 表示返回的string是一个回应（response），不是一个视图
        // @RequestParam 表示接收的参数可以是get或post

        User n = new User();
        n.setName(name);
        n.setEmail(email);
        userRepository.save(n);
        return "Saved";
    }

    @GetMapping(path="/all")
    public @ResponseBody Iterable<User> getAllUsers(HttpServletRequest request) {
    	HttpSession session = request.getSession();  
        // 返回一个json类型的user
        return userRepository.findAll();
    }
}